﻿'''eof
name:贷款及其他账户逾期总数
code:IC8_Mon3LoanCardQuerySum
tableName:
columnName:
groups:个人征信
dependencies:IC_DSJ
type:常用指标
dataSourceType:
eof'''
import re
import datetime
import sys
import json
import pandas as pd
import datetime
import traceback
reload(sys)
sys.setdefaultencoding('utf-8')

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)
    if occurTimes == 1:
        if len(table) == 0:
            return [{}]
        elif table is None or isinstance(table, list) is False:
            return None
        else:
            return data.get(tableName)


def value(x,y):
     null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
     if x.has_key(y) and isfloat(x[y])==True and x[y] not in null_type_list:
         return float(x[y])
     else:
         return 0


def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

def IC8_Mon3LoanCardQuerySum():
    data=IC_DSJ['data']
    returnList1 = []
    returnList2 = []
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') \
                          for i in [3, 0]]
    try:
        table1=getTable(data,"POQ",1)
        #查询记录信息单元
        PH01 = getTable(table1[0], 'PH01', 0)
        if table1 is None or table1==[{}]:
            return u"缺失值"
        if PH01 is None:
            return u'缺失值'
        elif PH01 == [{}]:
            return 0
        else:
            for i in PH01:
                    try:
                        #查询机构
                        PH010Q02=PH01[0].get('PH010Q02')
                        #查询日期
                        PH010R01=PH01[0].get('PH010R01')
                        queryDateFormat = Formate(PH010R01)
                        #查询原因
                        PH010Q03=PH01[0].get('PH010Q03')
                        if PH010Q02 in null_type_list or PH010R01 in null_type_list or PH010Q03 in null_type_list:
                            returnList1.append(None)
                            returnList2.append(None)
                            continue
                        if queryDateFormat>last_year_list[0] and queryDateFormat<=last_year_list[1] and PH010Q03 ==u"02-贷款审批":
                            returnList1.append(PH010Q02)
                            continue
                        if queryDateFormat>last_year_list[0] and queryDateFormat<=last_year_list[1] and PH010Q03 ==u"03-信用卡审批":
                            returnList2.append(PH010Q02)
                            continue
                        else:
                            returnList1.append(0)
                            returnList2.append(0)
                    except:
                        returnList1.append(None)
                        returnList2.append(None)
                        continue
            returnSet1 = set(returnList1)
            returnSet2 = set(returnList2)
            returnSet=list(returnSet1)+list(returnSet2)
            returnListNotNone = filter(lambda x:x is not None, returnSet)
            returnListNotZero = filter(lambda x:x != 0, returnListNotNone)

            if len(returnListNotNone) == 0:
                return u"缺失值"
            elif len(returnListNotZero) == 0:
                return 0
            else:
                return count(returnListNotZero)
    except:
        return u"缺失值"

result = IC8_Mon3LoanCardQuerySum()



